package com.amazon.shop.service.impl;

import com.amazon.shop.entity.auth.Permissions;
import com.amazon.shop.entity.auth.RolesPermissions;
import com.amazon.shop.entity.auth.Users;
import com.amazon.shop.entity.auth.UsersRoles;
import com.amazon.shop.mapper.PermissionsMapper;
import com.amazon.shop.mapper.RolesPermissionsMapper;
import com.amazon.shop.mapper.UsersMapper;
import com.amazon.shop.mapper.UsersRolesMapper;
import com.amazon.shop.service.PermissionsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 郭非
 * @since 2021-06-13
 */
@Service
public class PermissionsServiceImpl extends ServiceImpl<PermissionsMapper, Permissions> implements PermissionsService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private UsersRolesMapper usersRolesMapper;
    @Resource
    private RolesPermissionsMapper rolesPermissionsMapper;

    /**
     * 获取用户的权限列表
     *
     * @param token
     * @return
     */
    public boolean getPermissionList(String token, String permissionId) {
        //通过token查询用户信息
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("token", token);
        Users users = usersMapper.selectOne(usersQueryWrapper);

        //通过用户编号查询用户角色
        String userId = users.getUserId();
        QueryWrapper<UsersRoles> usersRolesQueryWrapper = new QueryWrapper<>();
        usersRolesQueryWrapper.eq("user_id", userId);
        UsersRoles usersRoles = usersRolesMapper.selectOne(usersRolesQueryWrapper);

        //通过角色编号查询角色权限
        String roleId = usersRoles.getRoleId();
        QueryWrapper<RolesPermissions> rolesPermissionsQueryWrapper = new QueryWrapper<>();
        rolesPermissionsQueryWrapper.eq("role_id", roleId);
        List<RolesPermissions> rolesPermissionsList = rolesPermissionsMapper.selectList(rolesPermissionsQueryWrapper);

        //返回权限编号列表
        List<String> list = rolesPermissionsList.stream().map((permission) -> {
            String permissionNumber = permission.getPermissionId();
            return permissionNumber;
        }).collect(Collectors.toList());

        //过滤需要权限编号
        List<String> collect = list.stream().filter(permission -> permissionId.equals(permission))
                .collect(Collectors.toList());

        //判断是否有需要权限编号
        if (collect.size() > 0) {
            return true;
        } else {
            return false;
        }
    }
}
